package kuzha;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public final class Utils {
	private Utils(){}
	
	public static <T> List<T> toList(T... items){
		List<T> result = new ArrayList<T>();
		for(T item: items) {
			result.add(item);
		}
		return result;
	}
	
	public static <T> String join(String sep, T... args) {
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < args.length; i++) {
			sb.append(args[i].toString());
			if (i < args.length - 1) {
				sb.append(sep);
			}
		}
		return sb.toString();
	}
	
	public static String readToEnd(Reader reader) throws IOException {
		BufferedReader rr = new BufferedReader(reader);
		StringBuilder script = new StringBuilder();
		String line = rr.readLine();
		while(line != null){
			script.append(line);
			script.append("\n");
			line = rr.readLine();
		}
		return script.toString();
	}
	
	public static String getFileName(String path) {
		if (path != null) {
			int index;
			index = path.lastIndexOf(File.pathSeparatorChar);
			if (0 <= index)
				path = path.substring(index + 1);
			index = path.lastIndexOf('/');
			if (0 <= index)
				path = path.substring(index + 1);
			index = path.lastIndexOf('\\');
			if (0 <= index)
				path = path.substring(index + 1);
		}
		return path;
	}
	public static String getFileNameWithoutExtension(String path) {
		path = getFileName(path);
		if (path != null) {
			int index;
			index = path.lastIndexOf(".");
			if (0 <= index)
				path = path.substring(0, index);
		}
		return path;
	}
	
	public static String getObjectId(Object obj) {
		return "0x" + Integer.toHexString(System.identityHashCode(obj)).toUpperCase();
	}
	
	public static String getObjectName(Class<? extends KuzhaObject> cls) {
		TypeName name = cls.getAnnotation(TypeName.class);
		if (name == null)
			return "object";
		else
			return name.value();
	}
	public static String getObjectName(KuzhaObject obj) {
		if (obj == null)
			return "void";
		return getObjectName(obj.getClass());
	}
	public static String toString(KuzhaObject obj) {
		return String.format("#%s(%s)", getObjectName(obj), getObjectId(obj));
	}
}
